<template>
  <div>
    <!-- 审计日志列表 -->
    <div v-show="!showdetail">
      <div class="topFlex">
        <div class="refresh">
          <el-button type="primary" title="同步资源" icon="el-icon-refresh" @click="refresh"></el-button>
        </div>
        <div class="timeBlock">
          <el-date-picker
            v-model="timeBlock"
            type="datetimerange"
            range-separator="至"
            start-placeholder="起始时间"
            end-placeholder="截止时间">
          </el-date-picker>
        </div>
        <!-- <div class="startPicker">
          <el-date-picker v-model="startTime" type="datetime" placeholder="起始时间"></el-date-picker>
        </div>
        <div class="endPicker">
          <el-date-picker v-model="endTime" type="datetime" placeholder="截止时间"></el-date-picker>
        </div> -->
        <div class="select">
          <el-select v-model="methodName" clearable placeholder="请选择请求方法">
            <el-option
              v-for="item in options"
              :key="item.methodName"
              :label="item.label"
              :value="item.methodName"
            ></el-option>
          </el-select>
        </div>
        <div class="search">
          <search placeholder="请输入操作人" :search-word.sync="operator" @search="onSearch" />
        </div>
        <div class="delete">
          <el-button 
          type="primary" 
          @click="onDelete"  
          icon="el-icon-delete"
          :loading="isDelete"
          >删除</el-button>
        </div>
      </div>

      <el-table
        ref="multipleTable"
        :data="pageList"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="loginName" label="操作人" width="120"></el-table-column>
        <el-table-column prop="requestUrl" label="请求网址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="requestMethod" label="请求方法" width="80"></el-table-column>
        <el-table-column prop="result" label="结果" width="200"></el-table-column>
        <el-table-column label="操作时间" width="200">
          <template slot-scope="scope">{{ scope.row.insDate }}</template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button
              @click.native.prevent="handleRow(scope.$index, pageList)"
              type="text"
              size="small"
              ><i class="el-icon-view icon-fs"></i></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button 
              @click.native.prevent="deleteRow(scope.row)" 
              type="text" 
              size="small"
            ><i class="el-icon-delete icon-fs"></i></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页(默认 10条/页) -->
      <div class="pagination-block">
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="sizeChange"
          :current-page.sync="currentPage"
          :page-sizes="pageSizes"
          layout="total, sizes, prev, pager, next, jumper"
          :total="auditNum"
          background
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { auditApi } from "@/request";
import { SET_LOGINER_ROLE } from "@/store/action-types";
import { mapState } from "vuex";
import Search from "@/components/common/Search.vue";
import { PAGE_SIZES } from "@/const";
import { sleep } from "@/utils";
let IS_PAGINATION_CHANGE = false
export default {
  name: "auditLog",
  components: { Search },
  computed: {
    ...mapState(["loginerRole"])
  },
  data() {
    return {
      pageSizes: PAGE_SIZES,
      pageList: [], //审计日志列表数据
      multipleSelection: [], //多选选中数据
      multipleIds: {}, //选中的id数组
      operator: "", //操作人
      timeBlock: [], //选中时间段
      options: [
        {
          methodName: "GET",
          label: "GET"
        },
        {
          methodName: "POST",
          label: "POST"
        },
        {
          methodName: "PUT",
          label: "PUT"
        },
        {
          methodName: "DELETE",
          label: "DELETE"
        },
        {
          methodName: "HEAD",
          label: "HEAD"
        },
        {
          methodName: "PATCH",
          label: "PATCH"
        },
        {
          methodName: "OPTIONS",
          label: "OPTIONS"
        },
        {
          methodName: "TRACE",
          label: "TRACE"
        }
      ], //请求方法下拉列表
      methodName: "", //请求方法
      currentPage: 1, // 当前页数
      auditNum: 0, // 列表项总条数
      showdetail: false, //是否查看详情
      detail: {}, //详情信息
      pageSize: 10, //分页码数
      loading: false, //是否loading转圈
      isDelete: false, //删除loading转圈
    };
  },
  methods: {
    //刷新按钮
    async refresh() {
      const empty = {
        beginTime: null,
        endTime: null,
        id: null,
        methodName: null,
        pageIndex: this.currentPage,
        pageSize: this.pageSize
      };
      this.loading = true;
      await sleep(500);
      auditApi
        .getAuditList(empty)
        .then(res => {
          this.pageList = res.pageList;
          this.auditNum = res.count;
          this.timeBlock = [];
          this.operator = "";
          this.methodName = "";
          this.username = "";
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
        });
    },
    //查询按钮
    onSearch() {
      // 提交查询
      this.getAuditList();
    },
    //删除按钮
    onDelete() {
      const params = {
        beginTime: this.timeBlock&&this.timeBlock[0] ? +new Date(this.timeBlock[0]) : null,
        endTime: this.timeBlock&&this.timeBlock[1] ? +new Date(this.timeBlock[1]) : null,
        username: this.operator ? this.operator : null,
        methodName: this.methodName ? this.methodName : null,
        ids: this.multipleIds.length > 0 ? this.multipleIds : null
      };
      // 判空
      if (
        this.timeBlock == [] &&
        this.operator == "" &&
        this.methodName == "" &&
        this.multipleIds == ""
      ) {
        this.$message({
          message: "删除内容不能为空！",
          type: "warning"
        });
        return;
      } else {
        this.$confirm("此操作将永久删除该日志, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.isDelete = true;
            auditApi.deleteAudit(params).then(res => {
              this.refresh();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.isDelete = false;
            });
          })
          .catch(() => {
            this.isDelete = false;
          });
      }
    },
    // 动态获取审计日志列表方法
    async getAuditList() {
      const params = {
        beginTime: this.timeBlock&&this.timeBlock[0] ? +new Date(this.timeBlock[0]) : null,
        endTime: this.timeBlock&&this.timeBlock[1] ? +new Date(this.timeBlock[1]) : null,
        username: this.operator ? this.operator : null,
        methodName: this.methodName ? this.methodName : null,
        pageIndex: this.currentPage,
        pageSize: this.pageSize
      };
      this.loading = true;
      await sleep(500);
      auditApi
        .getAuditList(params)
        .then(res => {
          this.pageList = res.pageList;
          this.auditNum = res.count;
          this.loading = false;
          this.$router.push(`/auditLog?pageIndex=${this.currentPage}`).catch(() => {})
          this.$nextTick(() => {
            IS_PAGINATION_CHANGE = false
          })
        })
        .catch(err => {
          this.loading = false;
          IS_PAGINATION_CHANGE = false
        });
    },
    // 多选框
    handleSelectionChange(val) {
      var str = "";
      val.map(function(item, index) {
        if (index == 0) {
          str += item.id;
        } else {
          str += "," + item.id;
        }
      });
      this.multipleSelection = val;
      this.multipleIds = str;
    },
    // 页码分页传值
    sizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handleCurrentChange();
    },
    // 分页
    handleCurrentChange(val, val2) {
      IS_PAGINATION_CHANGE = true
      this.getAuditList();
    },
    // 查看详情
    handleRow(index, rows) {
      console.log(rows[index]);
      this.$router.push(`/auditLogDetail/${rows[index].id}`)
      // const id = rows[index].id;
      // this.showdetail = !this.showdetail;
      // auditApi.getAuditDetail(id).then(res => {
      //   this.detail = res.data;
      // });
    },
    // 删除此条日志
    deleteRow(row) {
      let id = row.id;
      let params = {
        beginTime: this.timeBlock&&this.timeBlock[0] ? +new Date(this.timeBlock[0]) : null,
        endTime: this.timeBlock&&this.timeBlock[1] ? +new Date(this.timeBlock[1]) : null,
        username: this.operator ? this.operator : null,
        methodName: this.methodName ? this.methodName : null,
        ids: id ? id : null
      };
      this.$confirm("此操作将永久删除该日志, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          auditApi.deleteAudit(params).then(res => {
            this.refresh();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {})
    },
    getPageIndex() {
      const pageIndex = this.$route.query.pageIndex
      const index = Number(pageIndex)
      return index > 0 ? index : 1
    }
  },
  created() {
    this.currentPage = this.getPageIndex()
  },
  mounted() {
    this.getAuditList();
  },
  watch: {
    "$route.query.pageIndex": {
      handler(newVal, oldVal) {
        if (!IS_PAGINATION_CHANGE && oldVal) {
          this.currentPage = this.currentPage = this.getPageIndex()
          this.getAuditList()
        }
      }
    }
  }
};
</script>
<style scoped lang='scss'>
@import "~@/styles/variables.scss";
.test {
  height: 300px;
}
.red {
  color: $red;
}
.el-row {
  margin-bottom: 20px;
}
.topFlex {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
  .refresh {
    flex: 1;
  }
  .timeBlock,
  .select,
  .search,
  .delete {
    justify-self: flex-end;
    margin-left: 10px;
  }
}
/* 分页 */
.pagination-block {
  width: auto;
  margin-top: 20px;
  text-align: center;
}
</style>